package com.hckjsec.common.qiyuesuo;

import com.hckjsec.common.utils.StringUtils;
import com.qiyuesuo.sdk.v2.SdkClient;
import com.qiyuesuo.sdk.v2.bean.Contract;
import com.qiyuesuo.sdk.v2.bean.Signatory;
import com.qiyuesuo.sdk.v2.bean.Stamper;
import com.qiyuesuo.sdk.v2.bean.User;
import com.qiyuesuo.sdk.v2.exception.BaseSdkException;
import com.qiyuesuo.sdk.v2.http.StreamFile;
import com.qiyuesuo.sdk.v2.json.JSONUtils;
import com.qiyuesuo.sdk.v2.request.*;
import com.qiyuesuo.sdk.v2.response.*;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

public class SendByCodeSetting {

    public static final String SUBJECT = "公证文书签署";
    /**
     * 配置合同草稿
     *
     * @param client
     * @return
     * @throws Exception
     */
    public static SdkResponse<Contract> draftHks(SdkClient client,List<QysUser> qysUserList) throws Exception {
        Contract draftContract = new Contract();
        draftContract.setSubject(SUBJECT);
        draftContract.setSend(false); // 不发起合同
        draftContract.setOrdinal(false);
        qysUserList.forEach(befor -> {
            // 个人签署方
            Signatory persoanlSignatory = new Signatory();
            persoanlSignatory.setTenantType("PERSONAL");
            persoanlSignatory.setTenantName(befor.getName());
            persoanlSignatory.setSerialNo(0);
            if("1".equals(befor.getType())){
                persoanlSignatory.setReceiver(new User(befor.getPhone(), "MOBILE"));
            }else{
                persoanlSignatory.setReceiver(new User(befor.getMailbox(), "EMAIL"));
            }
            draftContract.addSignatory(persoanlSignatory);
        });
        String response = null;
        try {
            response = client.service(new ContractDraftRequest(draftContract));
        } catch (Exception e) {
            throw new Exception("创建合同草稿请求服务器失败，失败原因：" + e.getMessage());
        }
        SdkResponse<Contract> sdkResponse = JSONUtils.toQysResponse(response, Contract.class);
        if (!sdkResponse.getCode().equals(0)) {
            throw new Exception("创建合同草稿失败，失败原因：" + sdkResponse.getMessage());
        }
        return sdkResponse;
    }


    /**
     * 添加文书
     *
     * @param client
     * @return
     * @throws Exception
     */
    public static SdkResponse<DocumentAddResult> addDocumentByFileHks(SdkClient client, Long contractId, String path, String name)
            throws Exception {
        // 进入本地文件
        StreamFile file = new StreamFile(new FileInputStream(new File(path)));
        String response = null;
        try {
            // PDF为本地文件的类型，请修改为对应的本地文件类型
            response = client.service(new DocumentAddByFileRequest(contractId, file, "pdf", name));
        } catch (Exception e) {
            throw new Exception("根据文件添加文档请求服务器失败，失败原因：" + e.getMessage());
        }
        SdkResponse<DocumentAddResult> sdkResponse = JSONUtils.toQysResponse(response, DocumentAddResult.class);
        if (!sdkResponse.getCode().equals(0)) {
            throw new Exception("根据文件添加文档失败，失败原因：" + sdkResponse.getMessage());
        }
        return sdkResponse;
    }

    /**
     * 添加坐标
     *
     * @param client
     * @return
     * @throws Exception
     */
    public static Stamper sendStamper1Hks(SdkClient client, Contract draft, Long documentId1, String name, String page, String docTop,String docLeft,String pdfwidth,String pdfheight){
        Long personalSignatoryId = null;
        for (Signatory signatory : ((Contract) draft).getSignatories()) {
            if (signatory.getTenantType().equals("PERSONAL")) {
                if(name.equals(signatory.getTenantName())){
                    personalSignatoryId = signatory.getId();
                }
            }
        }
        double OffsetX=dateProcessing(StringUtils.StringToFloat(docLeft),StringUtils.StringToFloat(pdfwidth));
        double OffsetY=dateProcessing(StringUtils.StringToFloat(docTop),StringUtils.StringToFloat(pdfheight));
        Stamper personalStamper = new Stamper();
        personalStamper.setType("PERSONAL");
        personalStamper.setSignatoryId(personalSignatoryId);
        personalStamper.setDocumentId(documentId1);
        personalStamper.setOffsetX(OffsetX);
        personalStamper.setOffsetY((1-OffsetY-0.05));
        personalStamper.setPage(Integer.parseInt(page));
        return personalStamper;
    }
    /**
     * 发起合同
     *
     * @param client
     * @return
     * @throws Exception
     */
    public static SdkResponse sendHks(SdkClient client, Contract draft,List<Stamper> Stamperlist) throws Exception {
        String response = null;
        try {
            response = client.service(new ContractSendRequest(draft.getId(),Stamperlist));
        } catch (Exception e) {
            throw new Exception("发起合同请求服务器失败，失败原因：" + e.getMessage());
        }
        SdkResponse sdkResponse = JSONUtils.toQysResponse(response);
        if (!sdkResponse.getCode().equals(0)) {
            throw new Exception("发起合同失败，失败原因：" + sdkResponse.getMessage());
        }
        return sdkResponse;
    }



    /**获取人员令牌
     * @param client
     * @param contractId
     * @param documentId1
     * @param documentId2
     * @return
     * @throws Exception
     */
    public static String getUserKey(SdkClient client,QysUser qysUser)
            throws Exception {
        String userKeys="";
        UserAuthMiniappTicketRequest request = new UserAuthMiniappTicketRequest();
        if("1".equals(qysUser.getType())){
            request.setUser(new User(qysUser.getPhone(), "MOBILE"));
        }else{
            request.setUser(new User(qysUser.getMailbox(), "EMAIL"));
        }
        request.setMode("IVS");
        request.setPaperType("IDCARD");
        request.setBankMobile(qysUser.getPhone());
        request.setUsername(qysUser.getName());
        request.setIdCardNo(qysUser.getCertificatesnumber());
        String response = null;
        try {
            response = client.service(request);
        } catch (Exception e) {
            throw new BaseSdkException("调用接口错误，错误原因："+e.getMessage());
        }
        SdkResponse<MiniappTicketResult> result = JSONUtils.toQysResponse(response, MiniappTicketResult.class);
        userKeys=result.getResult().getTicket();
        if(!result.getCode().equals(0)) {
            throw new BaseSdkException("获取个人认证Ticket失败，失败原因："+result.getCode()+","+result.getMessage());
        }
        System.out.println(userKeys);
        return userKeys;
    }

    /**
     * 详情
     *
     * @param client
     * @param contractId
     * @return
     * @throws Exception
     */
    public static String gerenateSignUrl(SdkClient client,Long contractid,QysUser qysUser) throws Exception {
        // 合同页面
        String qsUrl="";
        ContractPageRequest request = new ContractPageRequest();
        request.setContractId(contractid);
        request.setCallbackPage("");
        if("1".equals(qysUser.getType())){
            request.setUser(new User(qysUser.getPhone(), "MOBILE"));
        }else{
            request.setUser(new User(qysUser.getMailbox(), "EMAIL"));
        }
        String response = client.service(request);
        SdkResponse<ContractPageResult> responseObj = JSONUtils.toQysResponse(response, ContractPageResult.class);
        if(responseObj.getCode() == 0) {
            ContractPageResult result = responseObj.getResult();
            qsUrl=result.getPageUrl();
        }
        return qsUrl;
    }
    /**
     * 获取签字文书dockey
     *
     * @param client
     * @param contractId
     * @return
     * @throws Exception
     */
    public static String getKeyHks(SdkClient client, long documentId1,QysUser qysUser) throws Exception {
        ContractMiniappTicketRequest request = new ContractMiniappTicketRequest();
        request.setContractId(documentId1);
        if("1".equals(qysUser.getType())){
            request.setUser(new User(qysUser.getPhone(), "MOBILE"));
        }else{
            request.setUser(new User(qysUser.getMailbox(), "EMAIL"));
        }
        String response = null;
        String keys="";
        try {
            response = client.service(request);
        } catch (Exception e) {
            throw new BaseSdkException("调用接口错误，错误原因：" + e.getMessage());
        }
        SdkResponse<MiniappTicketResult> result = JSONUtils.toQysResponse(response, MiniappTicketResult.class);
        keys=result.getResult().getTicket();
        if (!result.getCode().equals(0)) {
            throw new BaseSdkException("获取合同签署Ticket失败，失败原因：" + result.getCode() + "," + result.getMessage());
        }
        return keys;
    }

    /**
     * 判断是否认证过
     *
     * @param client
     * @param contractId
     * @return
     * @throws Exception
     */
    public static boolean getIsAuth(SdkClient client,QysUser qysUser) throws Exception {
        boolean falg=false;
        UserAuthResultRequest request = new UserAuthResultRequest();
        if("1".equals(qysUser.getType())){
            request.setUser(new User(qysUser.getPhone(), "MOBILE"));
        }else{
            request.setUser(new User(qysUser.getMailbox(), "EMAIL"));
        }
        String response = client.service(request);
        SdkResponse <UserAuthResult> responseObj = JSONUtils.toQysResponse(response, UserAuthResult.class);
        if(responseObj.getCode() == 0) {
            falg=responseObj.getResult().getRealName();
        }
        return falg;
    }
    public static void main(String[] args) {
        String serverUrl = "https://openapi.qiyuesuo.cn";
        String accessKey = "EA9Ww51Fbr";
        String accessSecret = "TiUA8Nb3f5t6Tg2s89VRcnNFJ7qXLY";
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        QysUser qysUser=new QysUser();
        qysUser.setType("2");
        qysUser.setPhone("704098070@qq.com");
        try {
            System.out.println(getIsAuth(sdkClient,qysUser));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





    public static double dateProcessing(float member,float denominator){
        double num =(double)member/denominator;
        DecimalFormat df = new DecimalFormat("0.00");
        return Double.valueOf(df.format(num)).doubleValue();
    }
}
